package cn.itcast.bos.web.action;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.service.FixedAreaService;
import cn.itcast.bos.web.action.common.BaseAction;

@ParentPackage(value = "json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class FixedAreaAction extends BaseAction<FixedArea> {

	private static final long serialVersionUID = 1L;

	@Autowired
	private FixedAreaService fixedAreaService;

	// 保存定区
	@Action(value = "fixedArea_save", results = {
			@Result(name = "success", type = "redirect", location = "./pages/base/fixed_area.html") })
	public String save() {
		fixedAreaService.save(model);
		return SUCCESS;

	}

	// 分页查询
	@Action(value = "fixedArea_pageQuery", results = { @Result(name = "success", type = "json") })
	public String pageQuery() {
		// 有条件的查询
		Pageable pageable = new PageRequest(page - 1, rows);
		// 组织查询条件
		Specification<FixedArea> specification = new Specification<FixedArea>() {

			@Override
			public Predicate toPredicate(Root<FixedArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate predicate = null;
				List<Predicate> list = new ArrayList<Predicate>();
				// 快递员工号
				if (StringUtils.isNotBlank(model.getId())) {
					Predicate p = cb.equal(root.get("id").as(String.class), model.getId());
					list.add(p);
				}
				// 所属单位
				if (StringUtils.isNotBlank(model.getCompany())) {
					Predicate p = cb.like(root.get("company").as(String.class), "%" + model.getCompany() + "%");
					list.add(p);
				}

				if (list != null && list.size() > 0) {
					Predicate[] p = new Predicate[list.size()];
					query.where(list.toArray(p));
				}
				// 按照id降序
				query.orderBy(cb.desc(root.get("id").as(String.class)));
				return query.getRestriction();
			}

		};

		Page<FixedArea> page = fixedAreaService.findPageQueryCondition(specification, pageable);
		pushPageDataToValueStack(page);
		return SUCCESS;

	}
}
